/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.database.dao;

import org.codeminer.database.DatabaseConnection;
import org.codeminer.database.DatabaseException;
import org.codeminer.parts.database.sql.SQL;
import org.codeminer.parts.library.Artwork;
import org.codeminer.parts.library.Song;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public final class ArtworkDAO extends DAO {

    public static String getArtwork(Song song, DatabaseConnection connection) throws DatabaseException {
        ResultSet resultSet = null;
        connection.accuireReadLock();
        try {
            String select = SQL.select("MD5").from("ARTWORKS").where("Song_Id").is(song.getOid()).toSQL();
            resultSet = connection.createStatement().executeQuery(select);
            if (resultSet.next()) {
                return resultSet.getString("MD5");
            } else {
                return null;
            }
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        } finally {
            connection.releaseReadLock();
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException ignored) {

                }
            }
        }
    }

    private ArtworkDAO() {
    }

    public static void storeArtwork(Song song, Artwork artwork, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(song);
        String insert = SQL.insertInto("ARTWORKS").values().value(song.getOid()).value(artwork.getMd5()).toSQL();
        connection.accuireWriteLock();
        try {
            executeInsert(connection, insert);
        } finally {
            connection.releaseWriteLock();
        }
    }
}
